package com.yjhb.android.sbz.activity.publishtask;

import android.Manifest;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.activity.BaseActivity;
import com.yjhb.android.sbz.activity.rule.RulePublishActivity;
import com.yjhb.android.sbz.adapter.StepSettingAdapter;
import com.yjhb.android.sbz.dialog.PublishStepDialog;
import com.yjhb.android.sbz.dialog.TipsDialog;
import com.yjhb.android.sbz.entity.AddTask;
import com.yjhb.android.sbz.entity.Task;
import com.yjhb.android.sbz.entity.TaskStep;
import com.yjhb.android.sbz.mvp.publishtask.PublishTaskPresenter;
import com.yjhb.android.sbz.mvp.publishtask.PublishTaskView;
import com.yjhb.android.sbz.tool.EventMsg;
import com.yjhb.android.sbz.tool.Tool;
import com.jojo.android.zxlib.tool.Global;
import com.jojo.android.zxlib.tool.ZxActivityTool;
import com.jojo.android.zxlib.tool.ZxDBHelper;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.jojo.android.zxlib.view.PopupWindowUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;
import com.yanzhenjie.recyclerview.touch.OnItemStateChangedListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

import static com.yjhb.android.sbz.Conf.REQUEST_IMAGE;

/**
 * 创建者 zx
 * 创建时间 2020/11/25 10:35
 */
public class StepSettingActivity extends BaseActivity<PublishTaskPresenter> implements OnItemMoveListener, OnItemStateChangedListener, View.OnClickListener, PublishStepDialog.OnSubmitListener, StepSettingAdapter.OnItemClickListener, PublishTaskView {
    private final String TAG = "StepSettingActivity";

    @BindView(R.id.swipe_recyclerview)
    SwipeRecyclerView swipe_recyclerview;
    @BindView(R.id.check_iv)
    ImageView check_iv;
    @BindView(R.id.publish_rule_tv)
    TextView publish_rule_tv;
    @BindView(R.id.protocol_tv)
    View protocol_tv;

    StepSettingAdapter stepSettingAdapter;

    TipsDialog tipsDialog;
    PublishStepDialog publishStepDialog;

    ArrayList<TaskStep> taskSteps;
    private PopupWindow popupWindow;

    private AddTask addTask;
    private int editMode; //0新增 1修改 2 重新发布

    @Override
    protected PublishTaskPresenter initPresenter() {
        return new PublishTaskPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_step_setting;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                // 获取返回的图片列表
                List<String> paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (paths != null)
                    EventBus.getDefault().post(new EventMsg("image_selected", paths));
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(EventMsg msg) {
        if ("request_select_img".equals(msg.msg)) {
            new RxPermissions(this).request(Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            MultiImageSelector.create(StepSettingActivity.this)
                                    .showCamera(false) // 是否显示相机. 默认为显示
                                    .count(1) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                                    .single() // 单选模式
                                    .multi() // 多选模式, 默认模式;
                                    .start(StepSettingActivity.this, REQUEST_IMAGE);
                        }
                    });
        }

    }

    @Override
    protected void initUI() {
        addTask = (AddTask) getIntent().getSerializableExtra("addTask");
        editMode = getIntent().getIntExtra("editMode", PublishActivity.MODE_ADD);
        if (addTask == null) {
            ZxToast.showFAILBottomToast("找不到任务！");
            Global.getInstance().getMainHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 1000);
            return;
        }
        if (addTask.getSteps() != null) {
            taskSteps = (ArrayList<TaskStep>) addTask.getSteps();
        } else {
            taskSteps = new ArrayList<>();
        }
        if (editMode == PublishActivity.MODE_REPUBLISH || editMode == PublishActivity.MODE_MODIFY) {
            check_iv.setSelected(true);
        }
        updateIcon();
        swipe_recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        swipe_recyclerview.setLongPressDragEnabled(true);
        swipe_recyclerview.setItemViewSwipeEnabled(true);
        stepSettingAdapter = new StepSettingAdapter(this);
        stepSettingAdapter.setData(taskSteps);
        swipe_recyclerview.setAdapter(stepSettingAdapter);
        tipsDialog = new TipsDialog(this);
        publishStepDialog = new PublishStepDialog(this, 1);

    }


    @Override
    protected void regEvent() {
        swipe_recyclerview.setOnItemMoveListener(this);
        swipe_recyclerview.setOnItemStateChangedListener(this);
        stepSettingAdapter.setOnItemClickListener(this);
        publishStepDialog.setOnSubmitListener(this);
    }


    @Override
    protected void initData() {

    }

    private void updateIcon() {
        check_iv.setImageResource(check_iv.isSelected() ? R.mipmap.icon_rule_selected : R.mipmap.icon_rule_unselected);
    }

    /**
     * 给步骤排序
     */
    private void stepSort() {
        for (int i = 0; i < taskSteps.size(); i++) {
            taskSteps.get(i).setSort(i);
        }
    }

    private void showTypePopup() {
        if (popupWindow == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.popup_step_type, null, false);
            popupWindow = PopupWindowUtil.CreatePopupWindow(this, view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            view.findViewWithTag(getString(R.string.step_type_internetSite)).setOnClickListener(this);
            view.findViewWithTag(getString(R.string.step_type_qrCode)).setOnClickListener(this);
            view.findViewWithTag(getString(R.string.step_type_imageAndCharacter)).setOnClickListener(this);
            view.findViewWithTag(getString(R.string.step_type_character)).setOnClickListener(this);
            view.findViewWithTag(getString(R.string.step_type_copyData)).setOnClickListener(this);
            view.findViewWithTag(getString(R.string.step_type_collectImage)).setOnClickListener(this);
            view.findViewWithTag(getString(R.string.step_type_collectInfo)).setOnClickListener(this);
        }
        WindowManager.LayoutParams params = this.getWindow().getAttributes();
        params.alpha = 0.4f;
        this.getWindow().setAttributes(params);
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
    }


    @Override
    public void onClick(View v) {
        if (v.getTag() != null) {
            String tag = v.getTag().toString();
            if (tag.equals(getString(R.string.step_type_internetSite))) {
                publishStepDialog.show(1);
            } else if (tag.equals(getString(R.string.step_type_qrCode))) {
                publishStepDialog.show(2);
            } else if (tag.equals(getString(R.string.step_type_imageAndCharacter))) {
                publishStepDialog.show(3);
            } else if (tag.equals(getString(R.string.step_type_character))) {
                publishStepDialog.show(4);
            } else if (tag.equals(getString(R.string.step_type_copyData))) {
                publishStepDialog.show(5);
            } else if (tag.equals(getString(R.string.step_type_collectImage))) {
                publishStepDialog.show(6);
            } else if (tag.equals(getString(R.string.step_type_collectInfo))) {
                publishStepDialog.show(7);
            }
            if (popupWindow != null) {
                popupWindow.dismiss();
            }

        }
    }


    @OnClick(R.id.back)
    public void back() {
        onBackPressed();
    }

//    @OnClick(R.id.check_iv)
//    public void check_iv() {
//        check_iv.setSelected(!check_iv.isSelected());
//        updateIcon();
//    }

    @OnClick(R.id.protocol_tv)
    public void protocol_tv() {
        check_iv.setSelected(!check_iv.isSelected());
        updateIcon();
    }

    @OnClick(R.id.publish_rule_tv)
    public void publish_rule_tv() {
        ZxActivityTool.skipActivity(this, RulePublishActivity.class);
    }


    @Override
    public void onBackPressed() {
//        tipsDialog.setTitle("提示");
//        tipsDialog.setCancelable(true);
//        tipsDialog.setCanceledOnTouchOutside(true);
//        tipsDialog.setContent("已编辑的步骤将会遗失，确定返回？");
//        tipsDialog.setSubmitColor(getResources().getColor(R.color.red_3b));
//        tipsDialog.setSubmitText("确定");
//        tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
//            @Override
//            public void onClick(int type) {
//                if (type == TipsDialog.TYPE_SUBMIT) {
//                    finish();
//                }
//                tipsDialog.dismiss();
//            }
//        });
//        tipsDialog.show();
        if (editMode == PublishActivity.MODE_ADD || editMode == PublishActivity.MODE_REPUBLISH) {
            saveTaskStep(addTask.getSteps());
        }
        setResult(RESULT_UPDATE);
        finish();
    }

    private void saveTaskStep(List<TaskStep> steps) {
        ZxDBHelper.getInstance().deleteForEq(TaskStep.class, "dbId", addTask.getTask().getDbId());
        ZxDBHelper.getInstance().createTableIfNotExists(Task.class);
        ZxDBHelper.getInstance().insert(TaskStep.class, steps);
    }

    private void clearTask() {
        ZxDBHelper.getInstance().deleteForEq(Task.class, "dbId", addTask.getTask().getDbId());
        ZxDBHelper.getInstance().deleteForEq(TaskStep.class, "dbId", addTask.getTask().getDbId());
    }

    @OnClick(R.id.preview_tv)
    public void preview_tv() {
        Tool.startPreviewTaskDetailActivity(this, addTask.getTask(), (ArrayList<TaskStep>) addTask.getSteps());
    }

    @OnClick(R.id.publish_btn)
    public void publish_btn() {
        if (!check_iv.isSelected()) {
            ZxToast.showBottomToastLight("请先阅读并同意《发布规则》");
            return;
        }
        if (taskSteps.size() < 1) {
            ZxToast.showBottomToastLight("请先添加步骤。");
            return;
        }
        boolean isHasInputType = false;
        for (TaskStep step : taskSteps) {
            if (step.getType() == 6 || step.getType() == 7) {
                isHasInputType = true;
            }
        }
        if (!isHasInputType) {
            ZxToast.showBottomToastLight("您需要添加“收集信息”相关步骤哦！如，上传截图、收集账号等。");
            return;
        }
        stepSort();
        tipsDialog.setCancelable(true);
        tipsDialog.setCanceledOnTouchOutside(true);
        tipsDialog.setTitle("提示");
        tipsDialog.setContent("确定提交悬赏？");
//        tipsDialog.setSubmitColor(getResources().getColor(R.color.yellow_31));
        tipsDialog.setSubmitText("提交悬赏");
        tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
            @Override
            public void onClick(int type) {
                tipsDialog.dismiss();
                if (type == TipsDialog.TYPE_SUBMIT) {
                    if (addTask == null) {
                        ZxToast.showBottomToastLight("任务不存在，退出后重试。");
                        return;
                    }
                    presenter.publishTask(addTask, editMode == PublishActivity.MODE_MODIFY);
                } else {
                }

            }
        });
        tipsDialog.show();
    }

    @OnClick(R.id.addStep_tv)
    public void addStep_tv() {
        showTypePopup();
    }


    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        ZxLogTool.i(actionState);

    }


    @Override
    public void onTaskStep(TaskStep step) {
        if (!taskSteps.contains(step)) {
            step.setDbId(addTask.getTask().getDbId());
            taskSteps.add(step);
        }
        stepSort();
//        stepSettingAdapter.notifyItemChanged(taskSteps.size() - 1);
        stepSettingAdapter.notifyDataSetChanged();
        saveTaskStep(taskSteps);
    }

    @Override
    public void onItemClick(TaskStep step) {
        if (publishStepDialog != null) {
            publishStepDialog.show(step.getType(), step);
        }
    }

    @Override
    public void onFailure(int code, String msg) {
        loadingDialog.cancel();
        if (code == 1110) {
            Tool.startRechargeActivity(this, 2, null, true);
            ZxToast.showBottomToastLight("您的余额不足，请充值！");
            return;
        }
        ZxToast.showBottomToastLight("悬赏提交失败：" + msg);
    }

    @Override
    public void onWait() {
        loadingDialog.setTipsText("请稍后...");
        loadingDialog.show();
    }

    @Override
    public void uploadingImg() {
        loadingDialog.setTipsText("图片上传中...");
    }

    @Override
    public void uploadCompleteImg() {
        loadingDialog.setTipsText("正在提交..");
    }

    @Override
    public void onSuccess(String data) {
        loadingDialog.cancel();
        ZxToast.showBottomToastLight("悬赏已提交，审核成功后将自动上架！");
        clearTask();
        setResult(RESULT_OK);
        finish();
        EventBus.getDefault().post(new EventMsg(EventMsg.TASK_PUBLISH_SUCCESS, null));
    }

    @Override
    public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
        Collections.swap(taskSteps, srcHolder.getAdapterPosition(), targetHolder.getAdapterPosition());
        stepSort();
        stepSettingAdapter.notifyItemMoved(srcHolder.getAdapterPosition(), targetHolder.getAdapterPosition());
        return true;
    }

    @Override
    public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {
        tipsDialog.setTitle("提示");
        tipsDialog.setContent("确定移除该步骤？");
        tipsDialog.setSubmitText("移除");
        tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
            @Override
            public void onClick(int type) {
                if (type == TipsDialog.TYPE_SUBMIT) {
                    taskSteps.remove(srcHolder.getAdapterPosition());
                    stepSort();
                    stepSettingAdapter.notifyItemRemoved(srcHolder.getAdapterPosition());
                } else {
                    stepSettingAdapter.notifyItemChanged(srcHolder.getAdapterPosition());
                }
                tipsDialog.dismiss();
            }
        });
        tipsDialog.show();
    }
}
